package com.dy.lock.screen.utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import com.dy.lock.screen.constants.Constant;
import com.dy.lock.screen.constants.GtPushCodeDes;
import com.gexin.rp.sdk.base.IPushResult;
import com.gexin.rp.sdk.base.impl.AppMessage;
import com.gexin.rp.sdk.base.impl.ListMessage;
import com.gexin.rp.sdk.base.impl.SingleMessage;
import com.gexin.rp.sdk.base.impl.Target;
import com.gexin.rp.sdk.exceptions.RequestException;
import com.gexin.rp.sdk.http.IGtPush;
import com.gexin.rp.sdk.template.TransmissionTemplate;

/**
 * 个推推送工具类
 * 
 * @author java
 * 
 */
public class GtPushUtil {

	protected static Logger log = Logger.getLogger(GtPushUtil.class);

	public static String host = "http://sdk.open.api.igexin.com/apiex.htm";
	public static String appId = "42fWoFR65B7XaklZFfuLu6";
	public static String appkey = "s71WOAfIVC7w04NsJIZad7";
	public static String master = "Xe4SEP8nFh6oZtxUPSWIR9";

	/**
	 * 针对个人用户推送消息
	 * 
	 * @param clientId
	 * @param content
	 * @return
	 * @throws Exception
	 */
	public static Map<String, Object> pushToSingle(String clientId,
			String content, String code) throws Exception {
		IGtPush push = new IGtPush(host, appkey, master);
		push.connect();

		TransmissionTemplate template = getTransmissionTemplate(content, code);

		SingleMessage message = new SingleMessage();
		message.setOffline(true);
		message.setOfflineExpireTime(Constant.MESSAGE_OFFLINE_EXPIRE_TIME);
		message.setData(template);
		// message.setPushNetWorkType(1); //根据WIFI推送设置

		Target target = new Target();
		target.setAppId(appId);
		target.setClientId(clientId);
		// target1.setAlias(Alias); //根据别名推送设置，CID与Alias可二选一进行推送

		IPushResult ret = null;
		try {
			ret = push.pushMessageToSingle(message, target);
		} catch (RequestException e) {
			ret = push.pushMessageToSingle(message, target, e.getRequestId());
			log.error("对单个用户推送消息异常重试", e);
		}
		if (ret != null) {
			Map<String, Object> result = ret.getResponse();

			return result;
		} else {
			log.error("对单个用户推送消息时，服务器响应异常");
			return null;
		}

	}

	/**
	 * 针对列表用户推送消息
	 * 
	 * @param clientIdList
	 * @param content
	 * @return
	 * @throws Exception
	 */
	public static Map<String, Object> pushToList(List<String> clientIdList,
			String content) throws Exception {
		// 配置返回每个用户返回用户状态，可选
		System.setProperty("gexin.rp.sdk.pushlist.needDetails", "true");

		IGtPush push = new IGtPush(host, appkey, master);
		push.connect();

		TransmissionTemplate template = getTransmissionTemplate(content, null);

		ListMessage message = new ListMessage();
		message.setOffline(true);
		message.setOfflineExpireTime(Constant.MESSAGE_OFFLINE_EXPIRE_TIME);
		message.setData(template);
		// message.setPushNetWorkType(1); //根据WIFI推送设置

		// 配置推送目标
		List<Target> targets = new ArrayList<Target>();
		if (clientIdList != null && !clientIdList.isEmpty()) {
			for (String clientId : clientIdList) {
				Target target = new Target();
				target.setAppId(appId);
				target.setClientId(clientId);
				targets.add(target);
			}
		}

		// 获取taskID
		String taskId = push.getContentId(message);
		// 使用taskID对目标进行推送
		IPushResult ret = push.pushMessageToList(taskId, targets);

		if (ret != null) {
			Map<String, Object> result = ret.getResponse();

			return result;
		} else {
			log.error("对列表用户推送消息时，服务器响应异常");
			return null;
		}

	}

	/**
	 * 
	 * 对指定应用群推消息 ，对单个或多个指定应用的所有用户群发推送消息。注：个推使用AppID来标识每个独立的应用。
	 * 
	 * @param appIdList
	 *            应用列表
	 * @param phoneTypeList
	 *            机型列表
	 * @param provinceList
	 *            省份列表
	 * @param tagList
	 *            标签列表
	 * @param content
	 *            透传内容
	 * @return
	 * @throws Exception
	 */
	public static Map<String, Object> pushToApp(List<String> appIdList,
			List<String> phoneTypeList, List<String> provinceList,
			List<String> tagList, String content) throws Exception {
		IGtPush push = new IGtPush(host, appkey, master);
		push.connect();

		TransmissionTemplate template = getTransmissionTemplate(content, null);
		AppMessage message = new AppMessage();
		message.setData(template);
		// 设置消息离线，并设置离线时间
		message.setOffline(true);
		// 离线有效时间，单位为毫秒，可选
		message.setOfflineExpireTime(Constant.MESSAGE_OFFLINE_EXPIRE_TIME);
		// 设置推送目标条件过滤
		if (appIdList == null || appIdList.isEmpty()) {
			appIdList = new ArrayList<String>();
			appIdList.add(appId);
		}
		if (phoneTypeList == null || phoneTypeList.isEmpty()) {
			phoneTypeList = new ArrayList<String>();
			// 设置机型
			phoneTypeList.add("ANDROID");
		}
		// if (provinceList == null || provinceList.isEmpty()) {
		// provinceList = new ArrayList<String>();
		// // 设置省份 33000000|浙江
		// provinceList.add("33000000");
		// }
		// if (tagList == null || tagList.isEmpty()) {
		// tagList = new ArrayList<String>();
		// // 设置标签内容
		// tagList.add("广告");
		//
		// }
		message.setAppIdList(appIdList);
		message.setPhoneTypeList(phoneTypeList);
		// message.setProvinceList(provinceList);
		// message.setTagList(tagList);

		IPushResult ret = push.pushMessageToApp(message);
		if (ret != null) {
			Map<String, Object> result = ret.getResponse();

			return result;
		} else {
			log.error("对app群用户推送消息时，服务器响应异常");
			return null;
		}

	}

	/**
	 * 获取透传模板信息
	 * 
	 * @param content
	 * @return
	 * @throws Exception
	 */
	public static TransmissionTemplate getTransmissionTemplate(String content,
			String code) throws Exception {
		TransmissionTemplate template = new TransmissionTemplate();
		// 设定接收的应用
		template.setAppId(appId);
		// 用于鉴定身份是否合法
		template.setAppkey(appkey);
		// 收到消息是否立即启动应用，1为立即启动，2则广播等待客户端自启动
		if (StringUtils.isNotBlank(code)
				&& GtPushCodeDes.REPEAT_LOGIN.getCode().equals(code)) {
			template.setTransmissionType(1);
		} else {
			template.setTransmissionType(2);
		}
		// 透传内容，不支持转义字符
		template.setTransmissionContent(content);
		// 设定iOS APN通知参数（包含两种接口形式，分别用于简单通知和复杂通知）
		// template.setPushInfo("dd", 1, "ddd", "com.gexin.ios.silence", "", "",
		// "", "");
		return template;
	}

	public static Map<String, String> map = new HashMap<String, String>();

	static {
		map.put("ok", "推送成功");
		map.put("successed_online", "用户在线，消息在线下发");
		map.put("successed_offline", "用户离线，消息存入离线系统");
		map.put("Error", "请求信息填写有误");
		map.put("action_error", "未找到对应的action动作");
		map.put("appkey_error", "Appkey填写错误");
		map.put("domain_error", "填写的域名错误或者无法解析");
		map.put("sign_error", "Appkey与ClientId不匹配，鉴权失败");
		map.put("AppidNoMatchAppKey", "appid和鉴权的appkey不匹配");
		map.put("PushTotalNumOverLimit", "推送消息个数总数超限");
		map.put("TokenMD5NoUsers", "在系统中未查找到用户");
		map.put("AppidNoAppSecret", "appid未找到对应的appSecret");
		map.put("AppidError", "clientid绑定的appid与推送的appid不符");
		map.put("flow_exceeded", "接口消息推送流量已超限");
		map.put("successed_ignore", "无效用户，消息丢弃");
		map.put("OtherError", "未知错误，无法判定错误类型");
		map.put("TaskIdHasBeanCanceled", "任务已经被CANCEL");
		map.put("NullMsgCommon", "未找到消息公共体");
		map.put("AppidError", "cid绑定的appId和sdk上传的appId不一致");
		map.put("flow_exceeded", "接口流量超限");
		map.put("PushMsgToListOrAppTimesOverLimit", "群推消息次数超限");
		map.put("TargetListIsNullOrSizeIs0", "目标用户列表为空");
		map.put("PushMsgToListOrAppTimesOverLimit", "群推次数超过最大值");
		map.put("AppIdNoUsers", "该AppId下的用户总数为0");
		map.put("SendError", "消息推送发送错误");
		map.put("SynSendError", "报文发送错误");
	}

}
